package com.tbit.uqbike.webmanager.controller;

import com.tbit.uqbike.constant.OperaPswConstant;
import com.tbit.uqbike.constant.UserConstant;
import com.tbit.uqbike.enums.SystemCodeEnum;
import com.tbit.uqbike.manager.exception.BaseException;
import com.tbit.uqbike.object.pojo.OssConfig;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.uqbike.service.business.OperaPswService;
import com.tbit.uqbike.service.business.OssConfigService;
import com.tbit.uqbike.webmanager.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import static com.tbit.uqbike.webmanager.controller.BaseController.getLogin;

/**
 * @Author: chen
 * @Description: 阿里云oss配置
 * @Date: 创建于 16:28 2020/8/3
 */
@RestController
@RequestMapping("/ossConfig")
public class OssConfigController {
    @Autowired
    private OssConfigService ossConfigService;
    @Autowired
    private OperaPswService operaPswService;

    @RequestMapping("/getByAccountId")
    public JsonResult getByAccountId(Integer accountId) {
        Assert.notNull(accountId, "ver.accountId.notNull");
        OssConfig ossConfig = ossConfigService.getByAccountId(accountId);
        return JsonResult.ok(ossConfig);
    }

    /**
     * 编辑 存在更新，不存在插入
     *
     * @param ossConfig
     * @param request
     * @param opeatePsw
     * @return
     */
    @RequestMapping("/insert")
    public JsonResult insert(OssConfig ossConfig, HttpServletRequest request, String opeatePsw) {
        Assert.notNull(ossConfig.getAccountId(), "ver.accountId.notNull");
        Assert.notNull(ossConfig.getBucketName(), "ver.oss.brandName.notNull");
        Assert.notNull(ossConfig.getEndpoint(), "ver.oss.endpoint.notNull");
        Assert.notNull(ossConfig.getAccessKeyId(), "ver.oss.accessKeyId.notNull");
        Assert.notNull(ossConfig.getAccessKeySecret(), "ver.oss.accessKeySecret.notNull");
        Assert.notNull(ossConfig.getBrandName(), "ver.oss.bucketName.notNull");

        /**操作密码校验*/
        if (!opeatePsw.equals(OperaPswConstant.ADMIN_OPERA_PSW)) {
            throw new BaseException(SystemCodeEnum.OPERA_PAW_ERROR);
        }

        check(request);
        ossConfigService.insert(ossConfig);
        return JsonResult.ok();
    }

    @RequestMapping("/edit")
    public JsonResult edit(OssConfig ossConfig) {
        Assert.notNull(ossConfig.getAccountId(), "ver.accountId.notNull");
        ossConfigService.edit(ossConfig);
        return JsonResult.ok();
    }

    /**
     * 权限校验
     */
    private void check(HttpServletRequest request) {
        LoginInfo loginInfo = getLogin(request);
        if (!loginInfo.type.equals(UserConstant.USER_ADMIN)) {
            throw new BaseException(SystemCodeEnum.NO_PRIVILEGE);
        }
    }
}
